import Client from '../Client'
import config from '../Config'

export default class BarrageClient extends Client {
  _keepLiveTime = 45

  constructor (room, port = 8506) {
    super('danmuproxy.douyu.com', port)
    this.room = room
  }

  _onOpen () {
    this._userLogin()
  }

  _onMessage (msg) {
    if (config._App.Debug) console.debug('receive msg', `[${msg.type}]`, msg)
    switch (msg.type) {
      case 'loginres':
        this.serverId = msg.sid
        if (this._keepLiveInterval) clearInterval(this._keepLiveInterval)
        this._keepLiveInterval = setInterval(this._keepLive.bind(this), 1e3 * this._keepLiveTime)
        this.once('close', () => clearInterval(this._keepLiveInterval))
        setTimeout(this._userJoinGroup.bind(this), 1e3)
        if (!this.hadLoginRes) this.hadLoginRes = true
        break
      case 'anbc':
      case 'dgb':
      case 'spbc':
        this.emit('pack', msg)
        break
    }
  }

  /* send msg pack */

  _userLogin () { // TODO 待改动
    this.sendMsg({
      type: 'loginreq',
      username: '',
      password: '1234567890123456',
      roomid: this.room,
      dfl: 'sn@A=105@Sss@A=1' // 屏蔽小礼物
    })
  }

  _keepLive () {
    this.sendMsg({
      type: 'mrkl'
    })
  }

  _userJoinGroup () {
    if (!this.isJoinGroup && this.isConnected) {
      this.isJoinGroup = true
      this.sendMsg({
        type: 'joingroup',
        rid: this.room,
        gid: 88 // 应该是只影响弹幕, 不影响礼物消息
      })
    }
  }
}
